const path = require('path');
const swig = require('swig');
const logger = require('morgan');
const express = require('express');
const createError = require('http-errors');
const session = require("express-session");
const swigfilter = require('./utils/filter');
const cookieParser = require('cookie-parser');
const config = require('config-lite')(__dirname);

const app = express();

swig.setDefaults({ cache: false, autoescape: false });
swigfilter(swig);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('view cache', false);
app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use('/public', express.static(__dirname + '/public'));
app.use('/uploads', express.static(__dirname + '/uploads'));

/*使用session中间件*/
app.use(session(config.session));

app.use(function(req, res, next) {
	res.locals.name = 'shinwen';
	next();
});
global.name = 'shinwen';

/*载入路由*/
app.use('/', require('./routes/index'));
app.use('/login', require('./routes/login'));
app.use('/common', require('./routes/common'));
app.use('/admin', require('./routes/admin'));
app.use('/story', require('./routes/story'));
app.use('/storytype', require('./routes/storytype'));
app.use('/capture', require('./routes/capture'));
app.use('/message', require('./routes/message'));
app.use('/user', require('./routes/user'));
app.use('/images', require('./routes/images'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	let err = createError(404);
	next(err);
});

// error handler
app.use(function(err, req, res, next) {
	// set locals, only providing error in development
	res.locals.error = req.app.get('env') === 'development' ? err : {};
	res.status(err.status || 500);
	if (err.status === 404) {
		res.locals.status = 404;
		res.locals.message = 'UH OH! 页面丢失';
		res.locals.content = '您所寻找的页面不存在。你可以点击下面的按钮，返回主页。';
		res.locals.btnname = '返回首页';
	} else {
		res.locals.status = 500;
		res.locals.message = '内部服务器错误';
		res.locals.content = '服务器代码错误，因而无法显示。你可以点击按钮刷新页面。';
		res.locals.btnname = '刷新页面';
	}
	res.render('error');
});

module.exports = app;